/**
 * Copyright 2022 Huawei Technologies Co., Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifndef NNACL_FP32_APPLY_PROXIMAL_ADAGRAD_SSE_H_
#define NNACL_FP32_APPLY_PROXIMAL_ADAGRAD_SSE_H_

#include "nnacl/intrinsics/ms_simd_instructions.h"
#include "nnacl/intrinsics/ms_simd_sse_instructions.h"

#ifdef __cplusplus
extern "C" {
#endif
#pragma GCC push_options
#pragma GCC target("sse4.1")
#define MS_SIMD_INSTRUCTION MS_SIMD_SSE_INSTRUCTION
#define BLOCK_NUM 4
#define MS_SIMD_SSE

static inline int64_t ApplyProximalAdagradOptSSE(
  int64_t index, float *var, float *accum, float lr, float l1, float l2, float *grad, int64_t size) {
  SIMD_F32 lr_vec = SIMD_MOV_F32(lr);
  SIMD_F32 l1_vec = SIMD_MOV_F32(l1);
  SIMD_F32 l2_vec = SIMD_MOV_F32(l2);
  for (int64_t block_max_size = size - BLOCK_NUM + 1; index < block_max_size; index += BLOCK_NUM) {
    SIMD_F32 tmp_vec1 = SIMD_LD_F32(grad + index);
    SIMD_F32 accum_vec = SIMD_LD_F32(accum + index);
    SIMD_F32 prox_v_vec = SIMD_LD_F32(var + index);

    accum_vec = SIMD_FMADD_F32(tmp_vec1, tmp_vec1, accum_vec);
    SIMD_F32 learn_rate_vec = SIMD_DIV_F32(lr_vec, SIMD_SQRT_F32(accum_vec));
    prox_v_vec = SIMD_SUB_F32(prox_v_vec, SIMD_MUL_F32(tmp_vec1, learn_rate_vec));
    SIMD_ST_F32(accum + index, accum_vec);
    tmp_vec1 = SIMD_FMADD_F32(l2_vec, learn_rate_vec, SIMD_MOV_F32(1));
    if (l1 > 0) {
      learn_rate_vec = SIMD_MUL_F32(learn_rate_vec, l1_vec);
      learn_rate_vec = SIMD_SUB_F32(SIMD_ABS_F32(prox_v_vec), learn_rate_vec);
      learn_rate_vec = SIMD_MAX_F32(learn_rate_vec, SIMD_MOV_F32(0.0f));
      learn_rate_vec = SIMD_DIV_F32(learn_rate_vec, tmp_vec1);

      SIMD_MASK greater_mask = SIMD_CMPGT_F32(SIMD_SET0_F32, prox_v_vec);
      SIMD_MASK less_mask = SIMD_CMPLT_F32(SIMD_SET0_F32, prox_v_vec);
      SIMD_F32 greater_v = SIMD_BLEND_F32(SIMD_MOV_F32(1), SIMD_SET0_F32, greater_mask);
      SIMD_F32 less_v = SIMD_BLEND_F32(SIMD_MOV_F32(1), SIMD_SET0_F32, less_mask);
      greater_v = SIMD_SUB_F32(greater_v, less_v);

      prox_v_vec = SIMD_MUL_F32(learn_rate_vec, greater_v);
    } else {
      prox_v_vec = SIMD_DIV_F32(prox_v_vec, tmp_vec1);
    }
    SIMD_ST_F32(var + index, prox_v_vec);
  }

  return index;
}

#undef MS_SIMD_INSTRUCTION
#undef BLOCK_NUM
#pragma GCC pop_options
#undef MS_SIMD_SSE
#ifdef __cplusplus
}
#endif
#endif
